package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    // 统计指定时间区间内的营业额数据
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        // 创建集合，用于存放日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        // 循环到结束日期
        while(!begin.equals(end)) {
            // 将日期添加到dateList集合中
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        // 创建集合，用于存放每天的营业额
        List<Double> turnoverList = new ArrayList<>();
        dateList.forEach(date -> {
            // 统计每个日期对应的营业额, 营业额为状态 = 已完成的订单金额合计
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            // select sum(amount) from orders where status = 5 and order_time < endTime and order_time > beginTime
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("endTime", endTime);
            map.put("beginTime", beginTime);
            Double turnover = orderMapper.sumByMap(map);
            turnoverList.add(turnover == null ? 0.0 : turnover);
        });
        // 组装并返回结果
        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        // 创建集合，用于存放日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        // 循环到结束日期
        while(!begin.equals(end)) {
            // 将日期添加到dateList集合中
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        // 创建集合，用于存放每天新增的用户数，和总用户数
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        for(LocalDate date : dateList) {
            // 统计每个日期对应的新增用户数
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("endTime", endTime);
            Integer totalUser = userMapper.countByMap(map);
            map.put("beginTime", beginTime);
            Integer newUser = userMapper.countByMap(map);
            newUserList.add(newUser);
            totalUserList.add(totalUser);
        }
        return UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        // 创建集合，用于存放日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        // 循环到结束日期
        while(!begin.equals(end)) {
            // 将日期添加到dateList集合中
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        // 创建集合，用于存放每天订单总数和有效订单数
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        // 遍历dateList日期集合，获取每个日期对应的有效订单数和订单总数
        for(LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            // 查询每天的订单总数
            Integer totalOrderCount = getOrderCount(beginTime, endTime, null);
            // 查询每天的有效订单数(即已完成订单)
            Integer validOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);
            orderCountList.add(totalOrderCount);
            validOrderCountList.add(validOrderCount);
        }
        // 计算时间区间内的订单总数量
        // 调用 reduce(Integer::sum) 方法对流中的所有元素进行累加操作
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();

        // 计算时间区间内的有效订单数量
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        // 计算订单完成率
        Double orderCompletionRate = 0.0;
        if(totalOrderCount != 0) {
            orderCompletionRate = (double) (validOrderCount / totalOrderCount);
        }



        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    // 统计销量排名前十的商品
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        log.info("beginTime: {}, endTime: {}", beginTime, endTime);
        // 查询销量排名前十的商品
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);
        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        return SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(names, ","))
                .numberList(StringUtils.join(numbers, ","))
                .build();
    }

    // 导出运营数据报表
    @Override
    public void exportBusinessData(HttpServletResponse response) throws IOException {
        // 查询数据库，获取营业数据 -- 最近30天的运营数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        // 查询数据库，获取营业数据 -- 当天运营数据
        LocalDate dateEnd = LocalDate.now().plusDays(1);
        LocalDateTime beginTime = LocalDateTime.of(dateBegin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(dateEnd, LocalTime.MAX);
        // 查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(beginTime, endTime);
        // 通过POI把查询到的数据写入excel文件
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        if(resourceAsStream == null) {
            throw new RuntimeException("文件不存在");
        }
        // 基于模板文件创建一个新的excel文件
        XSSFWorkbook excel = new XSSFWorkbook(resourceAsStream);
        // 获取第一个sheet页
        XSSFSheet sheet = excel.getSheet("Sheet1");
        // 填充数据--时间
        sheet.getRow(1).getCell(1).setCellValue(dateBegin + "至" + dateEnd);
        // 填充数据--营业额
        sheet.getRow(3).getCell(2).setCellValue(businessDataVO.getTurnover());
        // 填充数据--订单完成率
        sheet.getRow(3).getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
        // 填充数据--新增用户数
        sheet.getRow(3).getCell(6).setCellValue(businessDataVO.getNewUsers());
        // 填充数据--有效订单数
        sheet.getRow(4).getCell(2).setCellValue(businessDataVO.getValidOrderCount());
        // 填充数据--平均客单价
        sheet.getRow(4).getCell(4).setCellValue(businessDataVO.getUnitPrice());
        // 填充明细数据
        for (int i = 0; i < 30; i++) {
            // 获取当前日期
            LocalDate date = dateBegin.plusDays(i);
            // 获取某一天的营业数据
            BusinessDataVO businessDataList = workspaceService.getBusinessData(
                    LocalDateTime.of(date, LocalTime.MIN),
                    LocalDateTime.of(date, LocalTime.MAX)
            );
            // 把数据填充到excel中, 第8行开始
            // 日期
            sheet.getRow(7 + i).getCell(1).setCellValue(date.toString());
            // 营业额
            sheet.getRow(7 + i).getCell(2).setCellValue(businessDataList.getTurnover());
            // 有效订单数
            sheet.getRow(7 + i).getCell(3).setCellValue(businessDataList.getValidOrderCount());
            // 订单完成率
            sheet.getRow(7 + i).getCell(4).setCellValue(businessDataList.getOrderCompletionRate());
            // 平均客单价
            sheet.getRow(7 + i).getCell(5).setCellValue(businessDataList.getUnitPrice());
            // 新增用户数
            sheet.getRow(7 + i).getCell(6).setCellValue(businessDataList.getNewUsers());
            log.info("businessDataList: {},{}", businessDataList,date);
        }
        // 把生成的excel文件输出到浏览器
        ServletOutputStream outputStream = response.getOutputStream();
        excel.write(outputStream);
        outputStream.flush();
        // 关闭资源
        excel.close();
        outputStream.close();
    }

    // 根据状态统计订单数量
    private Integer getOrderCount(LocalDateTime beginTime, LocalDateTime endTime, Integer status) {
        Map map = new HashMap();
        map.put("beginTime", beginTime);
        map.put("endTime", endTime);
        map.put("status", status);
        return orderMapper.countByMap(map);
    }

}
